﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lipesin.MP710;

namespace Lipesin.SDT
{
	public partial class Main : Form
	{
		MP710Driver _mp710;
		SMDriver _mdriver;
		public Main()
		{
			InitializeComponent();
			_mp710 = new MP710Driver();
			_mdriver = new SMDriver(_mp710, new byte[] { 0, 1, 2, 3 });
			CheckBox box = chkPortControl;
			for (int i = 0; i < 16; i++)
			{
				box = new CheckBox();
				this.Controls.Add(box);
				box.Parent = grpDirect;
				box.Left = chkPortControl.Left;
				box.Top = chkPortControl.Top + i * (chkPortControl.Height + 5);
				box.Text = string.Format("Port {0:X0}", i);
				box.AutoSize = true;
				box.Tag = i.ToString();
				box.CheckedChanged += new EventHandler(chkPortControl_CheckedChanged);
			}
			grpDirect.Height = box.Bottom + 5;

			chkDirection.CheckState = _mdriver.DirectionForward ? CheckState.Checked : CheckState.Unchecked;
		}

		private void test1_Click(object sender, EventArgs e)
		{
			_mdriver.DirectionForward = true;
			int errors;
			double speed = 110;
			double time = 1;
			int count = Convert.ToInt32(speed * time);
			System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start();
			errors = _mdriver.DoSteps(count, speed, 0);
			sw.Stop();
			txtProtocol.Text = string.Format("{0}; {1}; {2}; {3}", sw.Elapsed.ToString(), count, errors, count / sw.Elapsed.TotalSeconds);
		}

		private void chkPortControl_CheckedChanged(object sender, EventArgs e)
		{
			CheckBox box = sender as CheckBox;
			_mp710.SetPort(Convert.ToByte(box.Tag), box.Checked);
		}

		private void btnExecute_Click(object sender, EventArgs e)
		{
			int errors;
			_mdriver.DirectionForward = chkDirection.Checked;
			System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start();
			errors = _mdriver.DoSteps(Convert.ToInt32(numCount.Value), Convert.ToDouble(numSpeed.Value), Convert.ToInt32(numAcceleration.Value));
			sw.Stop();
			List<string> protocol = new List<string>();
			protocol.Add(string.Format("Время выполнения: {0}", sw.Elapsed));
			protocol.Add(string.Format("Отставаний от ритма: {0}", errors));
			protocol.Add(string.Format("Средняя скорость: {0}", Convert.ToInt32(numCount.Value) / sw.Elapsed.TotalSeconds));
			txtProtocol.Text = string.Join(Environment.NewLine, protocol.ToArray());
		}
	}
}
